<template>
  <div class="content_box" :style="{paddingTop:isEdit?'0':'30rpx'}">
    <div class="steps_box" v-if="isEdit">
      <div class="nr">
        <div class="box on">
          <p class="num">1</p>
          <p class="text">创建店铺</p>
        </div>
        <div class="line_box">
          <p class="line"></p>
        </div>
        <div class="box">
          <p class="num">2</p>
          <p class="text">创建成功</p>
        </div>
      </div>
    </div>
    <div class="msg_box" :style="{marginTop:isEdit?'-100rpx':'0rpx'}">
      <!-- <div class="up_img">
        <p class="title">店铺头像</p>
        <van-uploader 
          max-count="1" 
          :file-list="fileList1" 
          @afterRead="afterRead1" 
          @delete="delOne1"
        />
      </div> -->
      <p class="title1">店铺头像</p>
      <div class="img_box">
          <div class="box" v-if="storeForm.headImg">
            <img @click="preview1(storeForm.headImg)" :src="storeForm.headImg" alt="">
            <p class="close" @click="close1">
              <van-icon name="cross" />
            </p>
          </div>
          <div class="up_img" @click="changeImg1" v-else>
            <p class="icon"><van-icon size="30px" name="plus" /></p>
            <p>上传图片</p>
          </div>
      </div>
      <p class="title1">店铺图片</p>
      <div class="img_box">
        <block v-if="storeForm.storeImg && storeForm.storeImg.length">
          <div class="box" v-for="(item,index) in storeForm.storeImg" :key="index">
            <img @click="preview(item)" :src="item" alt="">
            <p class="close" @click="close(index)">
              <van-icon name="cross" />
            </p>
          </div>
        </block>
        <div class="up_img" @click="changeImg">
          <p class="icon"><van-icon size="30px" name="plus" /></p>
          <p>上传图片</p>
        </div>
      </div>
      <!-- <div class="up_img">
        <p class="title">店铺图片</p>
        <van-uploader 
          max-count="3" 
          :file-list="fileList" 
          @afterRead="afterRead" 
          @delete="delOne"
        />
      </div> -->
      <div class="box">
        <p class="title">店铺名字</p>
        <p class="price">
          <input v-model.trim="storeForm.storeName" type="text" placeholder="请输入店铺名字">
        </p>
      </div>
      
      <!-- <div class="box">
        <p class="title">店铺状态</p>
        <picker bindchange="bindPickerChange" :range="array" range-key="name">
          <div class="picker">
            请选择
            <van-icon name="arrow" />
          </div>
        </picker>
      </div> -->
      <!-- <div class="box">
        <p class="title">经营城市</p>
        <div class="picker" @click="showCity = true">
          请选择
          <van-icon name="arrow" />
        </div>
      </div> -->
      <div class="box1" :style="{padding:storeForm.longitude?'20rpx 0':''}">
        <div>
          <p class="title">店铺地址</p>
          <span @click="changePlace" class="change_dz">选择地址</span>
        </div>
        <input v-if="storeForm.longitude" v-model.trim="storeForm.address" type="text" placeholder="请输入店铺地址">
      </div>
      <!-- <div class="box">
        <p class="title">店铺类型</p>
        <picker range-key="name" @change="typeChange" :range="array"  v-if="isEdit">
          <div class="picker">
            {{typeName}}
            <van-icon name="arrow" />
          </div>
        </picker>
        <p v-else>{{typeName}}</p>
      </div> -->
      <div class="box">
        <p class="title">创建人</p>
        <p class="price">
          <input v-model.trim="storeForm.name" type="text" placeholder="请输入负责人">
        </p>
      </div>
      <div class="box">
        <p class="title">创建人电话</p>
        <p class="price">
          <input v-model.trim="storeForm.mobile" type="text" placeholder="请输入联系人电话">
        </p>
      </div>
      <div class="box">
        <p class="title">低消时间</p>
        <p class="price">
          <input v-model.trim="lowConsumeTime" type="number" placeholder="请输入低消时间">
          小时
        </p>
      </div>
      <div class="box">
        <p class="title">wifi账号</p>
        <p class="price">
          <input v-model.trim="storeForm.wifiName" type="text" placeholder="请输入wifi账号">
        </p>
      </div>
      <div class="box">
        <p class="title">wifi密码</p>
        <p class="price">
          <input v-model.trim="storeForm.wifiPassword" type="text" placeholder="请输入wifi密码">
        </p>
      </div>
      <div class="jiesao">
        <p class="title">店铺介绍</p>
        <div>
          <textarea v-model.trim="storeForm.introduce" placeholder="输入房间介绍"></textarea>
        </div>
      </div>
      
      <div class="box">
        <p class="title">是否启用</p>
        <div class="yj">
          <p 
          @click="clickStatus(index)" 
          :class="statusIndex == index?'on':''" 
          v-for="(item,index) in status_list" :key="index">{{item.label}}</p>
        </div>
      </div>
    </div>
    <div class="anniu_box" :style="{paddingBottom:isIphoneXnum+'px'}">
      <div class="box" :style="{paddingBottom:isIphoneXnum+'px'}">
        <van-button 
          @click="submit"
          :disabled="loading"
          :loading="loading" 
          :loading-text="isEdit?'创建中...':'修改中...'"
          type="primary"
          color="#3d98f7"
          custom-style="box-shadow: 0rpx 10rpx 20rpx #CEDBFA;border:none;width: 100%;height: 88rpx;line-height: 88rpx;background: #1E68FF;border-radius: 100rpx;text-align: center;color: #fff;font-size: 30rpx;"
        >{{isEdit?'立即创建':'立即修改'}}</van-button>
      </div>
    </div>

    <!-- 城市弹窗 -->
    <van-action-sheet
      :show="showCity"
      @close="closeCityPop"
    >
    <div class="pop-city">
      <van-area 
        @cancel="closeCityPop"
        @confirm="cityChange"
        :area-list="areaList"  
        columns-placeholder="请选择经营城市"
      />
    </div>
    </van-action-sheet>
  </div>
</template>
 
<script>
import { getToken,getRefreshToken } from "@/utils/auth";
import { areaList } from '@vant/area-data';

import { 
  createStore,
  getStoreById,
  updateStore
} from "@/api/index";
export default {
  components: {},
  data() {
    return {
      showCity:false,
      areaList,
      loading:false,
      fileList: [],
      fileList1:[],
      storeForm:{
        headImg:'',
        storeImg:[], // 店铺图片
        storeName:'', // 店铺名字
        longitude:'',
        latitude:'',
        address:'',// 地址
        mobile:'',// 负责人电话
        name:'',// 负责人
        introduce:'',// 店铺介绍
        status:'use',// 店铺状态
        wifiName:'',
        wifiPassword:'',
        lowConsumeTime:''
      },
      lowConsumeTime:'',// 低消时间
      isIphoneXnum:0,
      status_list:[
        {
          value:'use',
          label:'启用',
        },
        {
          value:'stop',
          label:'不启用',
        }
      ],
      statusIndex:0,
      typeName:'请选择',
      isEdit:true,// true新增 false编辑

      storeId:'',//用于回显
    };
  },
  onShow() {

  },

  methods: {

    // 店铺信息回显
    async getStoreHx(){
      this.$showLoading("加载中...")
      await getStoreById({id:this.storeId}).then(res=>{
        if(res.statusCode == '00000'){
          wx.hideLoading()
          this.lowConsumeTime = res.data.lowConsumeTime/60
          // this.typeName = this.array.find(item=>item.id == res.data.storeTypeId).name
          this.storeForm = res.data
        }else{
          wx.hideLoading()
          this.$toast(res.message)
        }
      })
    },

    // 选择位置
    changePlace(){
      const _this = this
      wx.chooseLocation({
        success(chooseRes) {
          console.log(chooseRes)
          _this.storeForm.longitude = chooseRes.longitude
          _this.storeForm.latitude = chooseRes.latitude
          _this.storeForm.address = chooseRes.address
        }
      })
    },

    // 是否启用店铺
    clickStatus(index){
      this.statusIndex = index
      this.storeForm.status = this.status_list[index].value
    },

    // 获取验证码
    getCode(){
      if(this.codeLoading){
        return
      }
      this.codeLoading = true
      let int = setInterval(() => {
        this.codeNum--
        if(this.codeNum == 0){
          clearInterval(int)
          this.codeNum = 60
          this.codeLoading = false
        }
      }, 1000);
    },

    closeCityPop(){
      this.showCity = false
    },

    // 创建店铺提交
    submit(){
      console.log(this.storeForm)
      let phoneReg = /(^1[3|4|6|5|7|8]\d{9}$)|(^09\d{8}$)/;
      let zs = /^\+?[1-9][0-9]*$/;
      if(!this.storeForm.headImg){
        this.$toast('请上传店铺头像！') 
        return
      }
      if(!this.storeForm.storeImg.length){
        this.$toast('请上传店铺图片！') 
        return
      }
      if(!this.storeForm.storeName){
        this.$toast('请填写店铺名字') 
        return
      }
      if(!this.storeForm.address){
        this.$toast('请选择店铺地址') 
        return
      }
      if(!this.storeForm.name){
        this.$toast('请填写负责人') 
        return
      }
      if(!this.storeForm.mobile){
        this.$toast('请填写负责人电话') 
        return
      }
      if(!phoneReg.test(this.storeForm.mobile)){
        this.$toast('请填写正确的手机号') 
        return
      }
      if(!this.lowConsumeTime){
        this.$toast('请填写低消时间') 
        return
      }
      if(!zs.test(this.lowConsumeTime)){
        this.$toast('抵消时间必须为整数') 
        return
      }
      this.$showLoading(this.storeForm.id?'修改中...':'创建中...')
      this.loading = true
      this.storeForm.lowConsumeTime = this.lowConsumeTime*60
      let returnData = this.storeForm.id ? updateStore(this.storeForm) : createStore(this.storeForm)
      returnData.then(res=>{
        if(res.statusCode == '00000'){
          setTimeout(() => {
            this.loading = false
            if(this.storeForm.id){
              wx.navigateBack({ 
                delta: 1, 
              })
              this.$toast('修改成功')
              return
            }
            wx.navigateTo({
              url: `/pages/addStore/success/main?storeId=${res.data}`,
            });
          }, 1000);
        }else{
          wx.hideLoading()
          this.loading = false
          this.$toast(res.message)
        }
      })
    },

    // 删除图片-店铺
    close(index){
      let arr = []
      arr = this.storeForm.storeImg
      arr.splice(index, 1)
      this.storeForm.storeImg = []
      this.storeForm.storeImg = arr
    },

    // 图片预览-店铺
    preview(img){
      wx.previewImage({
        current: img, // 图片的地址url
        urls: this.storeForm.storeImg // 预览的地址url
      })
    },

    // 图片上传-店铺
    changeImg(){
      console.log("fdfdf")
      if(this.storeForm.storeImg.length >= 3){
        this.$toast('最多上传3张！')
        return
      }
      let arr = []
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success :(res)=>{
          wx.showLoading({title: '上传中...'})
          console.log(res)
          // tempFilePath可以作为img标签的src属性显示图片
          wx.uploadFile({
            url: 'https://gxegateway.jiuzhours.com/rich-sparrow-god/file/fileUpload',
            name: 'file',
            method: 'POST',
            filePath: res.tempFilePaths[0],
            header: {
              'Authorization': `Bearer ${getToken()}`,
              'refreshToken':getRefreshToken(),
            },
            formData: {
              file: res.tempFilePaths[0],
            },
            success: (res) => {
              this.$toast('上传成功！')
              let returnData = JSON.parse(res.data)
              arr.push(returnData.data)
              this.storeForm.storeImg = this.storeForm.storeImg.concat(arr)
            },
            fail: (err) => {
              console.log(err)
              this.$toast('上传失败，请重新上传！')
              wx.hideLoading()
            }
          })
          
        }
      })
    },

    /*==========店铺头像=============*/
    // 删除图片-头像
    close1(){
      this.storeForm.headImg = ''
    },

    // 图片预览-头像
    preview1(img){
      wx.previewImage({
        current: img, // 图片的地址url
        urls: img // 预览的地址url
      })
    },

    // 图片上传-头像
    changeImg1(){
      this.storeForm.headImg = ''
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success :(res)=>{
          wx.showLoading({title: '上传中...'})
          console.log(res)
          // tempFilePath可以作为img标签的src属性显示图片
          wx.uploadFile({
            url: 'https://gxegateway.jiuzhours.com/rich-sparrow-god/file/fileUpload',
            name: 'file',
            method: 'POST',
            filePath: res.tempFilePaths[0],
            header: {
              'Authorization': `Bearer ${getToken()}`,
              'refreshToken':getRefreshToken(),
            },
            formData: {
              file: res.tempFilePaths[0],
            },
            success: (res) => {
              this.$toast('上传成功！')
              let returnData = JSON.parse(res.data)
              this.storeForm.headImg = returnData.data
              console.log(this.storeForm.headImg)
            },
            fail: (err) => {
              console.log(err)
              this.$toast('上传失败，请重新上传！')
              wx.hideLoading()
            }
          })
          
        }
      })
    },
  },
  onLoad(options) {
    //判断手机机型，动态给底部添加样式
    console.log(options.isEdit)
    if(options.isEdit == '0'){
      this.isEdit = true
      wx.setNavigationBarTitle({
        title: '创建店铺',
      })
    }else{
      this.storeId = options.storeId
      this.isEdit = false
      wx.setNavigationBarTitle({
        title: '修改店铺',
      })
      // 回显
      this.getStoreHx()
    }
    wx.getSystemInfo({
      success: (res) => {
        console.log("手机信息res" + res.model);
        let modelmes = res.model;
        if (
          modelmes.search("iPhone 13") != -1 ||
          modelmes.search("iPhone 12") != -1 ||
          modelmes.search("iPhone 11") != -1 ||
          modelmes.search("iPhone X") != -1 ||
          modelmes.search("iPhone XR") != -1 ||
          modelmes.search("iPhone XS") != -1
        ) {
          this.isIphoneXnum = 25;
        } else {
          this.isIphoneXnum = 0;
        }
      },
    });

    
  },
  onHide() {},

  onUnload() {
    this.typeName = '请选择'
    this.storeForm = {
      headImg:'',
      storeImg:[], // 店铺图片
      storeName:'', // 店铺名字
      longitude:'',
      latitude:'',
      address:'',// 地址
      contactsPhone:'',// 负责人电话
      contacts:'',// 负责人
      introduce:'',// 店铺介绍
      status:'use',// 店铺状态
      storeTypeId:'',// 店铺类型ID
      detailedAddress:'',// 详细地址-门牌号
    }
  },
};
</script>

<style lang="scss" scoped>
.content_box{
  min-height: 100vh;
  background: #F7F7F7;
  .steps_box{
    padding:0 30rpx;
    height: 228rpx;
    background: #0274F1;
    .nr{
      height: 120rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .box{
      display: flex;
      align-items: center;
      .num{
        width: 40rpx;
        height: 40rpx;
        line-height: 40rpx;
        background: rgba(255,255,255,0.6);
        border-radius: 50%;
        font-size:30rpx;
        font-weight: 600;
        color:#0274F1;
        text-align: center;
      }
      .text{
        font-size:32rpx;
        color: rgba(255,255,255,0.6);
        font-weight: 600;
        margin-left:12rpx;
      }
      &.on{
        .num{
          background: rgba(255,255,255,1);
        }
        .text{
          color: rgba(255,255,255,1);
        }
      }
    }
    .line_box{
      width: 240rpx;
      height: 6rpx;
      background: rgba(255,255,255,0.4);
      border-radius: 4rpx;
      position: relative;
      .line{
        position: absolute;
        width: 120rpx;
        height: 6rpx;
        left: 0;
        top:0;
        background: #fff;
        border-radius: 4rpx;
      }
    }
  }
}
.msg_box{
  margin:-100rpx 30rpx 50rpx 30rpx;
  background: #fff;
  padding:0 30rpx;
  box-shadow: 0px 0px 16px 0px rgba(0,0,0,0.1);
  border-radius: 16rpx;
  .title1{
    padding:20rpx 0;
    font-size:30rpx;
    color:#222;
    font-weight: 500;
  }
  .img_box{
    display: flex;
    .box{
      display: inline-block;
      width: 150rpx;
      height: 150rpx;
      border-radius: 10rpx;
      position: relative;
      margin-right:30rpx;
      img{
        width: 100%;
        height: 100%;
        border-radius: 10rpx;
      }
      .close{
        position: absolute;
        top:-10rpx;
        right:-10rpx;
        width: 30rpx;
        height: 30rpx;
        background: #222;
        border-radius: 50%;
        font-size:20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        color:#fff;
      }
    }
    .up_img{
      display: inline-block;
      width: 150rpx;
      height: 150rpx;
      background: #F5F7FB;
      border-radius: 10rpx;
      text-align: center;
      color:#666;
      font-size:26rpx;
      .icon{
        margin-top:20rpx;
        margin-bottom:10rpx;
      }
    }
  }
  .box1{
    min-height: 100rpx;
    font-size:30rpx;
    color:#222;
    border-bottom:1px solid #f5f5f5;
    display: flex;
    justify-content: center;
    flex-direction:column;
    div{
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title{
        font-weight: 500;
      }
      .change_dz{
        border:1px solid #1E68FF;
        padding:0 20rpx;
        height: 50rpx;
        line-height: 50rpx;
        background: none;
        border-radius: 10rpx;
        text-align: center;
        color: #1E68FF;
        font-size: 28rpx;
      }
    }
    input{
      margin-top:10rpx;
    }
  }
  .box{
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size:30rpx;
    color:#222;
    border-bottom:1px solid #f5f5f5;
    .title{
      font-weight: 500;
      display: flex;
      align-items: center;
      span{
        display: inline-block;
        width: 30rpx;
        height: 30rpx;
        line-height: 30rpx;
        background: #1E68FF;
        border-radius: 50%;
        color:#fff;
        text-align: center;
        font-size:24rpx;
        margin-left:20rpx;
      }
    }
    .price{
      display: flex;
      align-items: center;
      input{
        text-align: right;
        margin-right:20rpx;
      }
  
    }
    .yj{
      display: flex;
      align-items: center;
      p{
        width: 140rpx;
        padding:8rpx 0;
        background: #F1F3F4;
        border-radius: 10rpx;
        font-size:28rpx;
        margin-right:30rpx;
        text-align: center;
      }
      .on{
        background: #1E68FF;
        color:#fff;
      }
      input{
        text-align: right;
        margin-right:20rpx;
        font-size:28rpx;
      }
      span{
        font-size:28rpx;
      }
    }
    .yy{
      display: flex;
      input{
        width: 140rpx;
        border:1px solid #dcdfe6;
        text-align: center;
        height: 60rpx;
        border-radius: 10rpx;;
        margin:0;
      }
      span{
        margin:0 20rpx;
      }
  
    }
  }
  .jiesao{
    font-size:30rpx;
    color:#222;
    border-bottom:1px solid #f5f5f5;
    padding:30rpx 0;
    font-weight: 500;
    .title{
      margin-bottom:30rpx;
    }
    div{
      background: #f5f5f5;
      padding:30rpx;
      height: 200rpx;
      border-radius: 10rpx;
      textarea{
        width: 100%;
        height: 100%;
        font-size:28rpx;
      }
    }
  }
}
.anniu_box{
  height: 150rpx;
  width: 100%;
  background: #fff;
  .box{
    width: 92%;
    height: 150rpx;
    line-height: 150rpx;
    position: fixed;
    bottom:0;
    left: 0;
    padding:0 30rpx;
    background: #fff;
    z-index: 100;
  }
}
</style>
